package com.warthur.spring.demo.framework.filter;

import com.warthur.spring.demo.pojo.domain.JwtAuthenticationToken;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author warthur
 * @date 2019/10/05
 */
public class JwtTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null || context.getAuthentication() == null) {
            String authToken = request.getHeader("Authorization");

            if (authToken != null) {

                // 设置security上下文，让security过滤器通过验证
                JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(jwtAuthenticationToken);
            }
        }

        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write("Exception");
        }
    }
}
